<template>
    <view class="section-selector-container">
        <view style="display: flex; justify-content: space-between; align-items: center">
            <view class="section-title">选择条田</view>
            <view class="all-select">
                <checkbox
                    :checked="allSelected"
                    :color="checkboxColor"
                    @click="toggleAll"></checkbox>
                <text>全选</text>
            </view>
        </view>

        <view class="section-grid">
            <view v-if="filteredSections.length === 0" class="empty-tip">
                <text>请先选择地块</text>
            </view>
            <view
                v-else
                v-for="(item, index) in sections"
                :key="index"
                :class="['section-item', { active: item.selected }]"
                v-show="isItemVisible(item)"
                @click="selectSection(index)">
                <text>{{ item.name }}</text>
            </view>
        </view>
    </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
    name: 'SectionSelector',
    props: {
        checkboxColor: {
            type: String,
            default: '#4062F6',
        },
    },
    data() {
        return {
            sections: [], // 所有条田数据
            allParcelFields: [], // 存储API返回的所有地块和条田数据
            selectedParcelIds: [], // 当前选中的地块ID
        }
    },
    created() {
        this.fetchFields()
    },
    computed: {
        ...mapGetters(['getParcelData', 'getUserInfo']),
        allSelected() {
            const visibleSections = this.filteredSections
            return (
                visibleSections.length > 0 && visibleSections.every((section) => section.selected)
            )
        },
        selectedSections() {
            return this.sections.filter((section) => section.selected)
        },
        // 根据选中的地块ID过滤条田
        filteredSections() {
            if (!this.selectedParcelIds || this.selectedParcelIds.length === 0) {
                return []
            }
            return this.sections.filter((section) =>
                this.selectedParcelIds.includes(section.parcelId)
            )
        },
        // 计算选中条田的面积总和
        selectedAreaSum() {
            const sum = this.selectedSections.reduce((sum, section) => {
                return sum + (section.surveyArea || 0)
            }, 0)
            return Math.round(sum) // 四舍五入为整数
        },
    },
    methods: {
        ...mapActions(['fetchParcelData']),
        async fetchFields() {
            try {
                uni.showLoading({ title: '加载条田数据...' })
                // 使用 store 中的方法获取数据
                const data = await this.fetchParcelData()

                if (data && data.length > 0) {
                    // 存储所有地块和条田数据
                    this.allParcelFields = data

                    // 初始化条田数据（所有地块的条田合并）
                    let allSections = []
                    data.forEach((parcel) => {
                        if (parcel.listField && parcel.listField.length > 0) {
                            parcel.listField.forEach((field) => {
                                allSections.push({
                                    id: field.id || field.fieldId,
                                    name: field.fieldName,
                                    parcelId: parcel.id,
                                    surveyArea: field.surveyArea || 0, // 添加面积字段
                                    userId: field.userId, // 负责人ID
                                    userName: field.userName, // 负责人姓名
                                    seedId: field.seedId, // 种子ID
                                    seedName: field.seedName, // 种子名称
                                    cropType: field.cropType, // 作物类型
                                    selected: false,
                                })
                            })
                        }
                    })

                    // 如果有条田数据，则使用API返回的数据
                    if (allSections.length > 0) {
                        this.sections = allSections
                    } else {
                        // 否则使用默认数据
                        this.initDefaultData()
                    }
                } else {
                    // 使用默认数据作为备选
                    this.initDefaultData()
                }
                uni.hideLoading()
            } catch (error) {
                console.error('获取条田数据失败', error)
                uni.hideLoading()
                uni.showToast({
                    title: '获取条田数据失败',
                    icon: 'none',
                })
                // 使用默认数据作为备选
                this.initDefaultData()
            }
        },

        // 初始化默认数据
        initDefaultData() {
            // 默认条田数据，当API请求失败或无数据时使用
            this.sections = [
                // { id: 1, name: "空条田", parcelId: 1, surveyArea: 0, selected: false },
            ]
        },

        // 检查条田是否应该显示
        isItemVisible(item) {
            if (!this.selectedParcelIds || this.selectedParcelIds.length === 0) {
                return false
            }
            return this.selectedParcelIds.includes(item.parcelId)
        },

        // 设置选中的地块ID
        setSelectedParcels(parcels) {
            console.log('设置选中的地块ID11', parcels)
            if (!parcels || parcels.length === 0) {
                this.selectedParcelIds = []
                return
            }

            // 提取地块ID
            this.selectedParcelIds = parcels.map((parcel) => parcel.id)
            console.log('设置选中的地块ID:', this.selectedParcelIds)
        },

        // 根据ID字符串设置选中状态
        setSelectedFields(idString) {
            console.log('根据ID字符串设置选中状态', idString)
            if (!idString) return

            const idArray = idString.split(',')

            this.sections.forEach((item) => {
                item.selected = idArray.includes(item.id.toString())
            })
        },

        selectSection(index) {
            this.sections[index].selected = !this.sections[index].selected
            // 选择条田时触发emit，传递面积总和
            this.$emit('areaChange', this.selectedAreaSum)
            // 把条田的负责人传回去  userId 、userName
            this.$emit('usersChange', this.getSectionUsers())

            // 把 "seedId": "0", "seedName": "大米1号" 传回去
            this.$emit('seedChange', this.getSectionSeed())
        },
        getSectionUsers() {
            const userMap = new Map()
            this.sections.forEach((section) => {
                if (section.selected && section.userId) {
                    userMap.set(section.userId, {
                        userId: section.userId,
                        userName: section.userName,
                    })
                }
            })
            const users = Array.from(userMap.values())
            // 如果没有选中的条田负责人，返回当前用户信息
            if (users.length === 0 && this.getUserInfo) {
                return [
                    {
                        userId: this.getUserInfo.id,
                        userName: this.getUserInfo.nickname,
                    },
                ]
            }
            return users
        },
        getSectionSeed() {
            const userMap = new Map()
            this.sections.forEach((section) => {
                if (section.selected && section.seedId) {
                    userMap.set(section.seedId, {
                        seedId: section.seedId,
                        seedName: section.seedName,
                        cropType: section.cropType,
                    })
                }
            })
            const users = Array.from(userMap.values())
            return users
        },
        toggleAll() {
            const newValue = !this.allSelected
            // 只切换当前可见的条田
            this.sections.forEach((section) => {
                if (this.isItemVisible(section)) {
                    section.selected = newValue
                }
            })
            // 全选/取消全选时触发emit，传递面积总和
            this.$emit('areaChange', this.selectedAreaSum)
            // 把条田的负责人传回去  userId 、userName
            this.$emit('usersChange', this.getSectionUsers())

            // 把 "seedId": "0", "seedName": "大米1号" 传回去
            this.$emit('seedChange', this.getSectionSeed())
        },

        // 获取选中的条田
        getSelectedSections() {
            return this.selectedSections
        },

        // 获取选中条田的面积总和
        getSelectedAreaSum() {
            return this.selectedAreaSum
        },

        // 验证是否有选中的条田
        validate() {
            return this.sections.some((section) => section.selected)
        },
    },
}
</script>

<style lang="scss" scoped>
.section-selector-container {
    background-color: #fff;
    margin-bottom: 20rpx;

    .section-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 20rpx;
    }

    .all-select {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        checkbox {
            margin-right: 10rpx;
            transform: scale(0.8);
        }

        text {
            font-size: 26rpx;
            color: #666;
        }
    }

    .section-grid {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 20rpx 10rpx;
        margin: 0;

        .empty-tip {
            width: 100%;
            height: 150rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 28rpx;
        }

        .section-item {
            padding: 20rpx 15rpx;
            width: auto;
            margin: 10rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f5f5;
            border-radius: 8rpx;
            word-break: break-all;

            text {
                font-size: 26rpx;
                color: #333;
            }

            &.active {
                background-color: #4062f6;

                text {
                    color: #fff;
                }
            }
        }
    }
}
</style>
